const { Controller } = require('egg')

const rule = {
	username: 'string',
	password: 'string',
	captcha: 'string',
}

/**
 * @controller login 登陆
 */
class LoginController extends Controller {
	/**
	 * @summary 登陆
	 * @description 登陆
	 * @router post /admin/login
	 * @request body loginRequest
	 */
	async index() {
		const ctx = this.ctx
		try {
			ctx.validate(rule, ctx.request.body)
			const data = await ctx.service.login.index(ctx.request.body)
			if (data.status === 'success') {
				const { username, password } = ctx.request.body
				const token = ctx.helper.getToken({ username, password })
				ctx.helper.success({
					token: token,
					id: data.id,
				})
			} else {
				ctx.helper.error(data.status)
			}
		} catch (e) {
			ctx.helper.error(e)
		}
	}
}

module.exports = LoginController
